package com.m.springblog.controller;

import com.m.springblog.model.Result;
import com.m.springblog.model.UserInfo;
import com.m.springblog.service.UserService;
import com.m.springblog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName, String password) {
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        UserInfo userInfo = userService.queryByName(userName);
        if (userInfo == null || userInfo.getId() < 0) {
            return Result.fail("用户不存在");
        }
        if (!password.equals(userInfo.getPassword())) {
            return Result.fail("用户名或密码错误");
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());
        String token = JwtUtils.genToken(claims);
        return Result.success(token);
    }

    /**
     * 获取登录用户信息
     * @return
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId == null) {return null;}

        return userService.queryById(userId);
    }

    /**
     * 获取博客作者信息
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        if (blogId == null || blogId < 0) {return null;}
        return userService.getAuthorInfo(blogId);
    }
}
